#include "volumetool.h"
#include "ui_volumetool.h"

#include <QGraphicsDropShadowEffect>
#include <QPainter>

VolumeTool::VolumeTool(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::VolumeTool)
{
    ui->setupUi(this);

    this->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);

    this->setAttribute(Qt::WA_TranslucentBackground);

    //窗口增加自定义阴影效果
    QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(this);
    shadowEffect->setColor("#646464");
    shadowEffect->setBlurRadius(10);
    shadowEffect->setOffset(0,0);

    this->setGraphicsEffect(shadowEffect);

    //设置按钮图标
    ui->silenceBtn->setIcon(QIcon(":/image/volumn.png"));

    connect(ui->silenceBtn,&QPushButton::clicked,this,&VolumeTool::onSilenceBtnClicked);

    //给volumBox安装事件拦截器,安装在当前界面: this
    ui->volumBox->installEventFilter(this);

}

VolumeTool::~VolumeTool()
{
    delete ui;
}

void VolumeTool::paintEvent(QPaintEvent *event)
{
    // 绘制volumeTool界面下面的三角
    QPainter painter(this);

    //1. 设置画笔
    painter.setPen(Qt::NoPen);

    //2. 设置画刷
    painter.setBrush(QBrush(Qt::white));

    QPolygon polygon;
    QPoint a(10 + 10,300 -5);
    QPoint b(10 + 80 - 10,300-5 );
    QPoint c(10+40,300 + 30-5);
    polygon.append(a);
    polygon.append(b);
    polygon.append(c);
    painter.drawPolygon(polygon);
}

void VolumeTool::onSilenceBtnClicked()
{
    this->isMuted = !(this->isMuted);

    //静音的图标发生改变
    if (isMuted)
    {
        ui->silenceBtn->setIcon(QIcon(":/image/silent.png"));
    }
    else
    {
        ui->silenceBtn->setIcon(QIcon(":/image/volumn.png"));
    }

    //媒体静音设置,发射信号交给MinMusic处理
    emit setMusicMuted(isMuted);
}

void VolumeTool::calVolume()
{
    //获取鼠标点击y坐标
    int height = ui->volumBox->mapFromGlobal(QCursor().pos()).y();
    //计算大小
    height = height < 25 ? 25 : height;
    height = height > 205 ? 205 : height;
    //更新outLine位置
    ui->outLine->setGeometry(ui->outLine->x(),height,ui->outLine->width(),180 + 25 - height);

    //更新silderBtn位置
    ui->silderBtn->move(ui->silderBtn->x(),height - ui->silderBtn->height() / 2);

    //计算音量大小
    volumeRatio = int(ui->outLine->height() / (float)180 * 100);

    //更新百分比
    ui->volumeRatio->setText(QString::number(volumeRatio) + "%");
}


bool VolumeTool::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->volumBox)
    {
        //事件发生在volumnBox控件上
        if (event->type() == QEvent::MouseButtonPress)
        {
            calVolume();
        }
        else if (event->type() == QEvent::MouseButtonRelease)
        {
            emit setMusicVolume(volumeRatio);
        }
        else if (event->type() == QEvent::MouseMove)
        {
            calVolume();
            emit setMusicVolume(volumeRatio);
        }

        return true;
    }

    return this->QObject::eventFilter(watched,event);
}
